package com.game.message.pb;

import com.game.message.transport.DataBuffer;
import com.google.protobuf.ByteString;
import io.netty.buffer.Unpooled;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * Created by Administrator on 2016/6/15.
 */
public class PBMessageTools {

	public static <T extends PBMessage> T decode(byte[] body, Class<T> clazz) {
		T pbMessage = null;
		try {
			pbMessage = clazz.newInstance();
			pbMessage.decode(new DataBuffer(Unpooled.wrappedBuffer(body)));
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return pbMessage;
	}

	public static MessageProto.Message encode(PBMessage pbMessage) {
		MessageProto.Message.Builder builder = MessageProto.Message.newBuilder();
		builder.setMsgId(pbMessage.getMsgId());
		builder.setSId(pbMessage.getsId());
		ByteString bs = ByteString.copyFrom(pbMessage.encode());
		builder.setBody(bs);
		MessageProto.Message build = builder.build();
		return build;
	}

	public static byte[] toMessageBytes(PBMessage message) {
		byte[] bytes = null;
		try {
			// object to bytearray
			ByteArrayOutputStream bo = new ByteArrayOutputStream();
			ObjectOutputStream oo = new ObjectOutputStream(bo);
			oo.writeObject(message);
			bytes = bo.toByteArray();
			bo.close();
			oo.close();
		} catch (Exception e) {
			System.out.println("translation" + e.getMessage());
			e.printStackTrace();
		}
		return bytes;
	}

	public static <T> T fromBytesToMessage(byte[] bytes) {
		Object obj = null;
		try {
			// bytearray to object
			ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
			ObjectInputStream oi = new ObjectInputStream(bi);

			obj = oi.readObject();
			bi.close();
			oi.close();
		} catch (Exception e) {
			System.out.println("translation" + e.getMessage());
			e.printStackTrace();
		}
		return (T)obj;
	}
}
